package com.guli.sms.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guli.common.pojo.SeckillSkuRelationEntity;
import com.guli.sms.service.SeckillSkuRelationService;
import com.guli.sms.vo.PromotionAndPromotionSession;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.guli.sms.mapper.SeckillPromotionMapper;
import com.guli.sms.entity.SeckillPromotionEntity;
import com.guli.sms.service.SeckillPromotionService;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;


@Service("seckillPromotionService")
public class SeckillPromotionServiceImpl extends ServiceImpl<SeckillPromotionMapper, SeckillPromotionEntity> implements SeckillPromotionService {

    @Resource
    SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public Page<SeckillPromotionEntity> queryPage(Integer currentPage, Integer size, Long promotionId) {

        Page<SeckillPromotionEntity> seckillPromotionEntityPage = new Page<>(currentPage,size);

        Page<SeckillPromotionEntity> page = this.page(seckillPromotionEntityPage);

        if(!ObjectUtils.isEmpty(promotionId)){
            SeckillPromotionEntity byId = this.getById(promotionId);

            List<SeckillPromotionEntity> collect = page.getRecords().stream().filter(promotion -> {
                return promotion.getId() != promotionId;
            }).collect(Collectors.toList());

            page.setRecords(collect);

            page.getRecords().add(byId);

        }


        return page;
    }

    @Override
    public Page<PromotionAndPromotionSession> getListBySecKillSessionId(Integer currentPage, Integer size,Long secKillSessionId) {
        Page<SeckillSkuRelationEntity> seckillSkuRelationEntityPage = seckillSkuRelationService.getSeckillRelationsBySeckillSessionId(secKillSessionId,currentPage,size);

        List<PromotionAndPromotionSession> collect = seckillSkuRelationEntityPage.getRecords().parallelStream().map(relation -> {

            PromotionAndPromotionSession promotionAndPromotionSession = new PromotionAndPromotionSession();

            promotionAndPromotionSession.setSeckillPromotionEntity(this.getById(relation.getPromotionSessionId()));

            promotionAndPromotionSession.setSeckillSkuRelationEntity(relation);

            return promotionAndPromotionSession;

        }).collect(Collectors.toList());

        Page<PromotionAndPromotionSession> promotionAndPromotionSessionPage = new Page<>();

        BeanUtils.copyProperties(seckillSkuRelationEntityPage,promotionAndPromotionSessionPage);

        promotionAndPromotionSessionPage.setRecords(collect);

        return promotionAndPromotionSessionPage;
    }


}